﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using AutoCopier.Extra;
using AutoCopier.Properties;
using Newtonsoft.Json;
using Starcraft2.ReplayParser;

namespace AutoCopier
{
    public partial class Form1 : Form
    {

        private Settings settings;
        private FileSystemWatcher watcher;
        

        public Form1()
        {
            InitializeComponent();
            var cp = Application.StartupPath;
            var fp = cp + "\\setting.json";
            if (File.Exists(fp))
            {
                string s = File.ReadAllText(fp);
                this.settings = (Settings)JsonConvert.DeserializeObject(s, typeof(Settings));
                settings.validExt = settings.validExt.RemoveNullOrWhiteSpace();
                this.btnSelectSource.Text = settings.srcFolder.Truncate(20);
                this.textBox1.Text = string.Join(",", settings.validExt);
                this.btnSelectDest.Text = settings.destFolder.Truncate(20);
                this.chkSc2.Checked = settings.IsSc2Mode;
            }
            else
            {
                this.settings = new Settings();
            }
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void btnSelectSource_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.Description = Resources.Form1_btnSelectSource_Click_Choose_a_source_folder___;
            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer;
            folderBrowserDialog1.ShowNewFolderButton = false;
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                btnSelectSource.Text = folderBrowserDialog1.SelectedPath.Truncate(20);
                settings.srcFolder = folderBrowserDialog1.SelectedPath;
                WriteSettings();
            }



        }

        private void btnSelectDest_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.Description = Resources.Form1_btnSelectDest_Click_Choose_a_destination_folder___;
            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Personal;
            folderBrowserDialog1.ShowNewFolderButton = false;
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                btnSelectDest.Text = folderBrowserDialog1.SelectedPath.Truncate(20);
                settings.destFolder = folderBrowserDialog1.SelectedPath;
                WriteSettings();
            }
        }

        private void btnStart_Start(object sender, EventArgs e)
        {
            //lauching Watcher

            bool continueProcess = true;

            if (string.IsNullOrWhiteSpace(this.settings.srcFolder) && continueProcess)
            {
                MessageBox.Show(Resources.Form1_btnStart_Start_AutoCopier_cannot_start__Choose_a_source_folder_and_retry);
                continueProcess = false;
            }

            if (string.IsNullOrWhiteSpace(this.settings.destFolder) && continueProcess)
            {
                MessageBox.Show(Resources.Form1_btnStart_Start_AutoCopier_cannot_start__Choose_a_destination_folder_and_retry);
                continueProcess = false;
            }

            //verify source & destination folder exists
            if (!Directory.Exists(this.settings.srcFolder) && continueProcess)
            {
                MessageBox.Show(Resources.Form1_btnStart_Start_Source_directory_does_not_exists__Choose_another_one__or_create_it_manually__and_retry);
                continueProcess = false;
            }

            if (!Directory.Exists(this.settings.srcFolder) && continueProcess)
            {
                MessageBox.Show(Resources.Form1_btnStart_Start_Destination_directory_does_not_exists__Choose_another_one__or_create_it_manually__and_retry);
                continueProcess = false;
            }

            if (this.settings.validExt.Count == 0 && continueProcess)
            {
                continueProcess = !(MessageBox.Show(Resources.Form1_btnStart_Click_No_valid_extensions_chosen__All_new_file_from_source_folder_will_be_copier_to_destination_folder__Would_you_like_to_continue__, "Warning !!", MessageBoxButtons.OKCancel) != DialogResult.OK);

            }

            if (continueProcess)
            {
                //lauching Watcher
                watcher = new FileSystemWatcher();
                watcher.Path = settings.srcFolder;
                watcher.Changed += new FileSystemEventHandler(watcher_Changed);
                watcher.Created += new FileSystemEventHandler(watcher_Changed);
                watcher.Deleted += new FileSystemEventHandler(watcher_Changed);
                watcher.Renamed += new RenamedEventHandler(watcher_Renamed);

                watcher.EnableRaisingEvents = true;

                TaskbarIcon.ShowBalloonTip(3000, "Sauron is alive", "AutoCopier is now working",
                                           ToolTipIcon.None);
                TaskbarIcon_MouseDoubleClick(null, null);
                SetLocked();
            }
        }

        private void btnStart_Stop(object sender, EventArgs e)
        {
            watcher.EnableRaisingEvents = false;
            watcher = null;
            SetUnlocked();

        }
        void watcher_Renamed(object sender, RenamedEventArgs e)
        {
            TryCopyToDest(e.FullPath);
        }

        void watcher_Changed(object sender, FileSystemEventArgs e)
        {

           TryCopyToDest(e.FullPath);

        }


        private void TaskbarIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {

                Show();
                this.WindowState = FormWindowState.Normal;

            }
            else
            {
                Hide();
                TaskbarIcon.ShowBalloonTip(10000, "AutoCopier", "AutoCopier is now minimized", ToolTipIcon.Info);
                this.WindowState = FormWindowState.Minimized;
            }
        }

        private bool TryCopyToDest(string srcPath)
        {
            try
            {
                string ext = new string(Path.GetExtension(srcPath).ToLowerInvariant().ToCharArray().Skip(1).ToArray());
                if (this.settings.validExt.Contains(ext))
                {
                    //get file name
                    var fileName = Path.GetFileName(srcPath);
                    if (settings.IsSc2Mode)
                    {
                        Replay replay = Replay.Parse(srcPath);
                        string p1 = replay.Players[0].Name;
                        string p2 = replay.Players[1].Name;

                        string r1 = replay.Players[0].Race;
                        string r2 = replay.Players[1].Race;

                        string mapName = replay.Map;

                        string dateStr = string.Format("{0:ddMMyy }", replay.Timestamp);

                        fileName = string.Format("{0} vs {1}-{2}v{3}-{4}-{5}.sc2replay", p1, p2, r1.FirstOrDefault(), r2.FirstOrDefault(), mapName, dateStr);
                        string fileInfo = string.Format("{0} vs {1}, {2}v{3}, {4}", p1, p2, r1.FirstOrDefault(), r2.FirstOrDefault(), mapName);
                        var destPath = this.settings.destFolder + "\\" + fileName;
                        if (DoCopy(srcPath, destPath))
                        {
                            TaskbarIcon.ShowBalloonTip(5000,"New replay copied", fileInfo,ToolTipIcon.Info);
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        var destPath = this.settings.destFolder + "\\" + fileName;
                        if (DoCopy(srcPath, destPath))
                        {
                            TaskbarIcon.ShowBalloonTip(10000, "New file has been be copied", srcPath,
                                                 ToolTipIcon.Info);
                        }
                        else
                            return false;

                    }
                   
                 

                    return true;
                }

                return false;
            }
            catch (Exception)
            {

                return false;
            }
        }


        private  bool DoCopy(string srcPath, string destPath)
        {
            try
            {

                File.Delete(destPath);
                //copy
                File.Copy(srcPath, destPath, true);

                return true;
            }
            catch (Exception ex)
            {

                return false;
            }

        }
        private void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            var currentContent = textBox1.Text;
            var x = currentContent.Split(',').ToList();
            settings.validExt = new List<string>();
            foreach (var ext in x)
            {
                if (!string.IsNullOrEmpty(ext))
                    settings.validExt.Add(ext.ToLowerInvariant());
            }
            settings.validExt = settings.validExt.RemoveNullOrWhiteSpace();
            WriteSettings();
        }

        private void WriteSettings()
        {

            try
            {
                var cp = Application.StartupPath;
                var fp = cp + "\\setting.json";
                var s = JsonConvert.SerializeObject(settings);
                File.Delete(fp);

                File.WriteAllText(fp, s);
            }
            catch (Exception)
            {
                
                return;
            }
        }

        private void SetLocked()
        {
            this.btnSelectDest.Enabled = false;
            this.btnSelectSource.Enabled = false;
            this.textBox1.Enabled = false;
            this.btnStart.Text = "Stop";
            this.btnStart.Click += new EventHandler(btnStart_Stop);
            btnStart.Click -= btnStart_Start;
        }

        private void SetUnlocked()
        {
            this.btnSelectDest.Enabled = true;
            this.btnSelectSource.Enabled = true;
            this.textBox1.Enabled = true;
            this.btnStart.Text = "Start";
            this.btnStart.Click += new EventHandler(btnStart_Start);
            btnStart.Click -= btnStart_Stop;
        }

        private void quitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void TaskbarIcon_MouseDown(object sender, MouseEventArgs e)
        {
       
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.ApplicationExitCall) return;
            e.Cancel = true;
            TaskbarIcon_MouseDoubleClick(null, null);
        }

        private void chkSc2_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chkSend = (CheckBox) sender;
            if (chkSend.Checked)
            {
                this.settings.validExt.Clear();
                this.settings.validExt.Add("sc2replay");
                this.textBox1.Text = "sc2replay";
                this.textBox1.Enabled = false;
                this.settings.IsSc2Mode = true;
             
                WriteSettings();
            }
            else
            {
                this.textBox1.Enabled = true;
                this.settings.IsSc2Mode = false;
            }

            WriteSettings();
        }

  
    }
}
